import os
import json


class Sidebar:
    def __init__(self, name, dir, base, first_md):
        self.name = name
        self.dir = dir
        self.base = base
        self.first_md = first_md

    def toSideBarStr(self):
        return f"'/{self.name}/': getSidebarItems('{self.dir}','/{self.base}')"

    def toNavStr(self):
        names = self.name.split("/")
        return json.dumps({"text": names[-1], "link": f"/{self.name}/{self.first_md[:-3] if self.first_md else ''}"}, ensure_ascii=False)

    def __str__(self):
        return self.name


class Nav:
    def __init__(self, text, link, items=None):
        self.text = text
        self.link = link
        self.items = items

    def add_item(self, item):
        if item:
            if self.items == None:
                self.items = []
            self.items.append(item)

    def __str__(self):
        if self.items == None:
            return "{\"text\": \"%s\", \"link\": \"%s\"}" % (self.text, self.link)

        return "{\"text\": \"%s\", \n  \"items\": [%s]}" % (self.text,  ",\n    ".join([i.toNavStr() for i in self.items]))


def save_to_file(data, path="res/data.json",mode="w+"):
    with open(path, mode,encoding="utf-8") as f:
        if isinstance(data, str):
            f.write(data)
        else:
            f.write(json.dumps(data, indent=4, ensure_ascii=False))


def get_sidebar_tree(base_path):
    files = os.listdir(base_path)
    sidebar_list = []
    for file in files:
        cur_path_sidebar_list = []
        if file[0] == '.':
            continue
        firstSideBar = Sidebar(file, file, file, None)
        files_2 = os.listdir(os.path.join(base_path, file))
        for file2 in files_2:
            if file2.endswith(".md") and not firstSideBar.first_md:
                firstSideBar.first_md = file2
            if not os.path.isdir(os.path.join(base_path, file, file2)):
                continue
            value = os.path.join(file, file2)
            value = value.replace("\\", "/")
            curSideBar = Sidebar(value, value, value, None)
            for file3 in os.listdir(os.path.join(base_path, file, file2)):
                if file3[0] == '.':
                    continue
                if file3.endswith(".md") and not curSideBar.first_md:
                    curSideBar.first_md = file3
            if curSideBar.first_md:
                cur_path_sidebar_list.append(curSideBar)
        if firstSideBar.first_md:
            sidebar_list.append(firstSideBar)
        for i in cur_path_sidebar_list:
            sidebar_list.append(i)
    return sidebar_list


def get_nav_from_sidebar_tree(sidebar_list):
    navs = {}
    for item in sidebar_list:
        text = item.name.split("/")[0]
        if text in navs.keys():
            navs[text].append(item)
        else:
            navs[text] = [item]
    for key in navs.keys():
        nav = Nav(key, f'/{key}/')
        for i in navs[key]:
            nav.add_item(i)
        print(nav)
        save_to_file(str(nav)+",\n","res/nav.json","a+")
    


if __name__ == '__main__':
    base_path = "D:\code\myself\mayun\dhnote"
    sidebar_tree = get_sidebar_tree(base_path)
    save_to_file(",\n".join([i.toSideBarStr() for i in sidebar_tree]),path="res/sidebar.txt")
    get_nav_from_sidebar_tree(sidebar_tree)
    for file in os.listdir(os.path.join(base_path,"0_java","jvm")):
        print(file)
